//
//  QSValidateTool.swift
//  TestSwift
//
//  Created by Song on 2018/4/19.
//  Copyright © 2018年 Song. All rights reserved.
//

import UIKit

class QSValidateTool: NSObject {
    
    /// 字符串是否为空
    class func qs_isStringEmpty(_ string: String?) ->Bool {
        if let str = string {
            return str.isEmpty
        }
        return true
    }
    
    /// 数组是否为空
    class func qs_isArrayEmpty(_ array: Array<Any>?) ->Bool {
        if let arr = array {
            return arr.isEmpty
        }
        return true
    }
    
    /// 验证邮箱
    class func qs_validateEmail(_ email: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        
        return emailTest.evaluate(with: email)
    }
    
    /// 验证手机号以及固话方法
    class func qs_validatePhone(_ number: String) -> Bool {
        // 验证输入的固话中不带 "-"符号
        let phoneRegex = "^(0[0-9]{2,3})?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$|(^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$)"
        let phoneTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        
        let phone = number.replacingOccurrences(of: "-", with: "", options: .literal, range: nil)
        return phoneTest.evaluate(with: phone)
    }
    
    /// 验证网址
    class func qs_validateUrl(_ url: String) -> Bool {
        let urlRegex = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
        let urlTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", urlRegex)
        
        return urlTest.evaluate(with: url)
    }
    
    /// 验证身份证，只是粗略验证
    class func qs_validateIdentityCard(_ ID: String) -> Bool {
        let IDRegex = "(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)"
        let IDTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", IDRegex)
        
        return IDTest.evaluate(with: ID)
    }
    
    /// 验证密码，数字加字母，默认最少6位，最多16位
    ///
    /// - Parameters:
    ///   - pwd: 密码字符串
    ///   - leastDigit: 最少多少位
    ///   - mostDigit: 最多多少位
    class func qs_validatePassword(pwd: String, leastDigit: Int = 6, mostDigit: Int = 16) -> Bool {
        let passwordStr = "^(?!^\\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{\(leastDigit),\(mostDigit)}$"
        let passwordPre = NSPredicate(format: "SELF MATCHES %@", passwordStr)
        
        return passwordPre.evaluate(with: pwd)
    }
    
    /// 验证小数位数，默认两位
    ///
    /// - Parameters:
    ///   - number: 数字字符串
    ///   - decimals: 小数位数
    class func qs_validateNumber(_ number: String, decimals: Int = 2) -> Bool {
        let conditionStr = "^(0\\.\\d{0,\(decimals)}|[1-9][0-9]{0,}+\\.\\d{0,\(decimals)}|[1-9]\\d+|\\d)$"
        let numberPre = NSPredicate(format: "SELF MATCHES %@", conditionStr)
        
        return numberPre.evaluate(with: number)
    }
}
